import 'package:flutter/foundation.dart';

/// 🎯 活动实体模型
/// 
/// 核心业务对象，代表活动数据
/// 对应接口: POST /activities/nearby/
class ActivityEntity {
  /// 活动ID
  final int activityId;
  
  /// 活动标题
  final String activityTitle;
  
  /// 活动详情
  final String? activityDetails;
  
  /// 活动图片列表
  final List<String>? activityImages;
  
  /// 活动位置描述
  final String? activityLocation;
  
  /// 活动纬度
  final double? latitude;
  
  /// 活动经度
  final double? longitude;
  
  /// 活动发布时间
  final String? activityPublishTime;
  
  /// 活动类型标签
  final List<String>? activityType;
  
  /// 活动标签
  final List<String>? activityTags;
  
  /// 活动状态
  final List<String>? activityStatus;
  
  /// 活动性别限制
  final List<String>? activityRestriction;
  
  /// 最大参与人数
  final int? activityMaxParticipants;
  
  /// 当前参与人数
  final int? currentParticipants;
  
  /// 发布者ID
  final int? publisherId;
  
  /// 发布者昵称
  final String? publisherNickname;
  
  /// 发布者头像URL
  final String? publisherAvatar;
  
  /// 发布者性别
  final String? publisherGender;
  
  /// 发布者年龄
  final int? publisherAge;
  
  /// 发布者签名
  final String? publisherSignature;
  
  /// 发布者标签
  final List<String>? publisherTags;
  
  /// 发布者积分
  final int? publisherPoints;
  
  /// 发布者手机号
  final String? publisherPhone;
  
  /// 距离（公里）- 从当前位置计算
  final double? distance;
  
  /// 扩展数据（包含结束时间等）
  final Map<String, dynamic>? extraData;
  
  /// 创建时间
  final String? createTime;
  
  /// 更新时间
  final String? updateTime;
  
  ActivityEntity({
    required this.activityId,
    required this.activityTitle,
    this.activityDetails,
    this.activityImages,
    this.activityLocation,
    this.latitude,
    this.longitude,
    this.activityPublishTime,
    this.activityType,
    this.activityTags,
    this.activityStatus,
    this.activityRestriction,
    this.activityMaxParticipants,
    this.currentParticipants,
    this.publisherId,
    this.publisherNickname,
    this.publisherAvatar,
    this.publisherGender,
    this.publisherAge,
    this.publisherSignature,
    this.publisherTags,
    this.publisherPoints,
    this.publisherPhone,
    this.distance,
    this.extraData,
    this.createTime,
    this.updateTime,
  });
  
  /// 从JSON创建实例
  factory ActivityEntity.fromJson(Map<String, dynamic> json) {
    try {
      return ActivityEntity(
        activityId: json['activityId'] as int? ?? json['activity_id'] as int? ?? 0,
        activityTitle: json['activityTitle'] as String? ?? json['activity_title'] as String? ?? '',
        activityDetails: json['activityDetails'] as String? ?? json['activity_details'] as String?,
        activityImages: _parseStringList(json['activityImages'] ?? json['activity_images']),
        activityLocation: json['activityLocation'] as String? ?? json['activity_location'] as String?,
        latitude: _parseDouble(json['latitude']),
        longitude: _parseDouble(json['longitude']),
        activityPublishTime: json['activityPublishTime'] as String? ?? json['activity_publish_time'] as String?,
        activityType: _parseStringList(json['activityType'] ?? json['activity_type']),
        activityTags: _parseStringList(json['activityTags'] ?? json['activity_tags']),
        activityStatus: _parseStringList(json['activityStatus'] ?? json['activity_status']),
        activityRestriction: _parseStringList(json['activityRestriction'] ?? json['activity_restriction']),
        activityMaxParticipants: json['activityMaxParticipants'] as int? ?? json['activity_max_participants'] as int?,
        currentParticipants: json['currentParticipants'] as int? ?? json['current_participants'] as int? ?? json['activityCurrentParticipants'] as int?,
        publisherId: json['publisherId'] as int? ?? json['publisher_id'] as int?,
        publisherNickname: json['publisherNickname'] as String? ?? json['publisher_nickname'] as String?,
        publisherAvatar: json['publisherAvatar'] as String? ?? json['publisher_avatar'] as String?,
        publisherGender: json['publisherGender'] as String? ?? json['publisher_gender'] as String?,
        publisherAge: json['publisherAge'] as int? ?? json['publisher_age'] as int?,
        publisherSignature: json['publisherSignature'] as String? ?? json['publisher_signature'] as String?,
        publisherTags: _parseStringList(json['publisherTags'] ?? json['publisher_tags']),
        publisherPoints: json['publisherPoints'] as int? ?? json['publisher_points'] as int?,
        publisherPhone: json['publisherPhone'] as String? ?? json['publisher_phone'] as String?,
        distance: _parseDouble(json['distance']),
        extraData: json['extraData'] as Map<String, dynamic>? ?? json['extra_data'] as Map<String, dynamic>?,
        createTime: json['createTime'] as String? ?? json['create_time'] as String?,
        updateTime: json['updateTime'] as String? ?? json['update_time'] as String?,
      );
    } catch (e, stackTrace) {
      debugPrint('❌ ActivityEntity.fromJson 解析失败: $e');
      debugPrint('📍 JSON数据: $json');
      debugPrint('📍 错误堆栈: $stackTrace');
      rethrow;
    }
  }
  
  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'activityId': activityId,
      'activityTitle': activityTitle,
      'activityDetails': activityDetails,
      'activityImages': activityImages,
      'activityLocation': activityLocation,
      'latitude': latitude,
      'longitude': longitude,
      'activityPublishTime': activityPublishTime,
      'activityType': activityType,
      'activityTags': activityTags,
      'activityStatus': activityStatus,
      'activityRestriction': activityRestriction,
      'activityMaxParticipants': activityMaxParticipants,
      'currentParticipants': currentParticipants,
      'publisherId': publisherId,
      'publisherNickname': publisherNickname,
      'publisherAvatar': publisherAvatar,
      'publisherGender': publisherGender,
      'publisherAge': publisherAge,
      'publisherSignature': publisherSignature,
      'publisherTags': publisherTags,
      'publisherPoints': publisherPoints,
      'publisherPhone': publisherPhone,
      'distance': distance,
      'extraData': extraData,
      'createTime': createTime,
      'updateTime': updateTime,
    };
  }
  
  /// 辅助方法：解析字符串列表
  static List<String>? _parseStringList(dynamic value) {
    if (value == null) return null;
    
    if (value is List) {
      return value.map((e) => e.toString()).toList();
    }
    
    if (value is String) {
      // 尝试解析JSON数组字符串
      try {
        final list = value
            .replaceAll('[', '')
            .replaceAll(']', '')
            .replaceAll('"', '')
            .replaceAll("'", '')
            .split(',')
            .map((e) => e.trim())
            .where((e) => e.isNotEmpty)
            .toList();
        return list;
      } catch (e) {
        return [value];
      }
    }
    
    return null;
  }
  
  /// 辅助方法：解析double类型
  static double? _parseDouble(dynamic value) {
    if (value == null) return null;
    
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) {
      return double.tryParse(value);
    }
    
    return null;
  }
  
  /// 获取第一张图片URL
  String? get firstImage {
    if (activityImages != null && activityImages!.isNotEmpty) {
      return activityImages!.first;
    }
    return null;
  }
  
  /// 获取发布者性别图标
  String get genderIcon {
    if (publisherGender == '女') return '♀';
    return '♂';
  }
  
  /// 格式化距离显示
  String get distanceText {
    if (distance == null) return '距离未知';
    
    if (distance! < 0.1) {
      return '<100m';
    } else if (distance! < 1) {
      return '${(distance! * 1000).round()}m';
    } else if (distance! < 100) {
      return '${distance!.toStringAsFixed(1)}公里';
    } else {
      return '${distance!.round()}公里';
    }
  }
  
  /// 获取活动结束时间
  String? get activityEndTime {
    if (extraData != null) {
      return extraData!['activityEndTime'] as String? ?? 
             extraData!['activity_end_time'] as String?;
    }
    return null;
  }
  
  @override
  String toString() {
    return 'ActivityEntity(id: $activityId, title: $activityTitle, location: $activityLocation, distance: $distanceText)';
  }
}

